<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>采购统计 - 生产过程管理系统</title>
    <link rel="stylesheet" href="../../../css/style1.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/echarts@5.4.0/dist/echarts.min.css">
    <style>
        .submenu {
            display: none;
        }
        .menu-item.active > .submenu {
            display: block;
        }
        .menu-arrow {
            transition: transform 0.2s;
        }
        .menu-item.active > a > .menu-arrow {
            transform: rotate(90deg);
        }

        .form-row {
            display: flex;
            margin-bottom: 15px;
            flex-wrap: wrap;
            gap: 20px;
        }

        .form-group {
            flex: 1;
            min-width: 200px;
        }

        .form-group label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }

        .form-control {
            width: 100%;
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
        }

        .btn-container {
            display: flex;
            justify-content: flex-end;
            gap: 10px;
            margin-top: 20px;
        }

        .btn {
            padding: 8px 16px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }

        .btn-primary {
            background-color: var(--primary-color);
            color: white;
        }

        .btn-secondary {
            background-color: #f0f0f0;
            color: #333;
        }

        .btn:hover {
            opacity: 0.9;
        }

        .stat-container {
            display: flex;
            flex-wrap: wrap;
            gap: 20px;
            margin: 20px 0;
        }

        .stat-card {
            flex: 1;
            min-width: 300px;
            background-color: #fff;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }

        .stat-title {
            font-size: 16px;
            font-weight: bold;
            margin-bottom: 15px;
            padding-bottom: 10px;
            border-bottom: 1px solid #eee;
        }

        .chart-container {
            height: 300px;
            margin: 20px 0;
        }

        .table-container {
            overflow-x: auto;
            margin: 20px 0;
        }

        .stat-table {
            width: 100%;
            border-collapse: collapse;
        }

        .stat-table th, .stat-table td {
            border: 1px solid #ddd;
            padding: 12px;
            text-align: left;
        }

        .stat-table th {
            background-color: #f2f2f2;
            font-weight: bold;
        }

        .stat-table tr:nth-child(even) {
            background-color: #f9f9f9;
        }

        .filter-container {
            margin-bottom: 20px;
            display: flex;
            align-items: center;
            gap: 20px;
            flex-wrap: wrap;
        }

        .filter-item {
            display: flex;
            align-items: center;
            margin-bottom: 10px;
        }

        .filter-item label {
            margin-right: 10px;
            font-weight: bold;
        }

        .filter-item select, .filter-item input {
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            min-width: 150px;
        }

        .content-wrapper {
            padding: 20px;
            background: #fff;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            margin: 20px;
        }
    </style>
    <script src="https://cdn.jsdelivr.net/npm/echarts@5.4.0/dist/echarts.min.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function () {
            // 初始化左侧菜单
            var menuItems = document.querySelectorAll('.menu-item > a');
            menuItems.forEach(function (item) {
                item.addEventListener('click', function (e) {
                    var parent = item.parentElement;
                    document.querySelectorAll('.menu-item').forEach(function (el) {
                        if (el !== parent) el.classList.remove('active');
                    });
                    parent.classList.toggle('active');
                    e.preventDefault();
                });
            });

            // 正确选择物料管理菜单项（第二个菜单项）
            const materialMenuItems = document.querySelectorAll('.menu-item');
            if (materialMenuItems.length >= 2) {
                const materialMenuItem = materialMenuItems[2]; // 索引1对应第二个元素
                materialMenuItem.classList.add('active');
            } else {
                console.warn("未找到物料管理菜单项");
            }

            // 设置当前页面菜单项
            const submenuLinks = document.querySelectorAll('.submenu li a');
            let found = false;

            submenuLinks.forEach(link => {
                if (link.getAttribute('href') === 'material_statistics.html') {
                    link.classList.add('active');
                    found = true;
                }
            });

            if (!found) {
                console.warn("未找到当前页面对应的菜单链接");
            }

            // 加载统计数据
            loadStatistics();

            // 绑定搜索事件
            document.getElementById('search-btn').addEventListener('click', loadStatistics);
        });

        // 加载统计数据
        async function loadStatistics() {
            // 显示加载状态
            document.getElementById('application-table-body').innerHTML = '<tr><td colspan="6" style="text-align: center;">加载中...</td></tr>';

            try {
                const keyword = document.getElementById('keyword-search').value;

                // 构建API请求URL
                let apiUrl = 'http://localhost:8080/api/material-purchase/list';
                const queryParams = [];

                if (keyword) {
                    queryParams.push(`keyword=${encodeURIComponent(keyword)}`);
                }

                if (queryParams.length > 0) {
                    apiUrl += '?' + queryParams.join('&');
                }

                // 从API获取数据
                const response = await fetch(apiUrl);
                if (!response.ok) {
                    throw new Error(`API请求失败: ${response.status}`);
                }

                const purchaseData = await response.json();

                // 转换API数据为页面所需的统计格式
                const statistics = transformDataToStatistics(purchaseData);

                // 筛选数据
                if (keyword) {
                    statistics.applicationList = statistics.applicationList.filter(app =>
                        app.materialName.includes(keyword) || app.applicant.includes(keyword)
                    );
                }

                displayStatistics(statistics);
            } catch (error) {
                console.error('加载数据失败:', error);
                document.getElementById('application-table-body').innerHTML = `<tr><td colspan="6" style="text-align: center; color: #b91c1c;">加载数据失败: ${error.message}</td></tr>`;
            }
        }

        // 将API数据转换为页面所需的统计格式（移除部门相关）
        function transformDataToStatistics(purchaseData) {
            const statistics = {
                totalApplications: purchaseData.length,
                approvedApplications: 0,
                rejectedApplications: 0,
                pendingApplications: 0,
                materialTypeStats: [],
                applicationList: []
            };

            // 用于统计物料类型的数据结构
            const materialTypeMap = {};

            purchaseData.forEach(purchase => {
                // 转换数据为申请列表项（移除部门相关）
                const status = purchase.isApproved ? 'APPROVED' : 'PENDING';

                statistics.applicationList.push({
                    id: purchase.purchaseId,
                    materialName: purchase.materialName,
                    materialType: purchase.materialType,
                    quantity: purchase.purchaseQuantity,
                    applicant: purchase.applicantJobNumber,
                    applyDate: purchase.storageDate,
                    status: status
                });

                // 统计申请状态
                if (status === 'APPROVED') {
                    statistics.approvedApplications++;
                } else if (status === 'REJECTED') {
                    statistics.rejectedApplications++;
                } else {
                    statistics.pendingApplications++;
                }

                // 统计物料类型数据
                if (!materialTypeMap[purchase.materialType]) {
                    materialTypeMap[purchase.materialType] = { type: purchase.materialType, count: 0 };
                }
                materialTypeMap[purchase.materialType].count++;
            });

            // 转换物料类型统计数据为数组
            statistics.materialTypeStats = Object.values(materialTypeMap);

            return statistics;
        }

        // 显示统计数据
        function displayStatistics(statistics) {
            // 显示统计卡片
            document.getElementById('total-applications').textContent = statistics.totalApplications;
            document.getElementById('approved-applications').textContent = statistics.approvedApplications;
            document.getElementById('rejected-applications').textContent = statistics.rejectedApplications;
            document.getElementById('pending-applications').textContent = statistics.pendingApplications;

            // 渲染物料类型采购数量饼图
            const materialTypeChart = echarts.init(document.getElementById('material-type-chart'));
            const materialTypeOptions = {
                title: {
                    text: '各类型物料采购数量分布'
                },
                tooltip: {
                    trigger: 'item',
                    formatter: '{a} <br/>{b} : {c} ({d}%)'
                },
                series: [
                    {
                        name: '采购数量',
                        type: 'pie',
                        radius: '55%',
                        center: ['50%', '60%'],
                        data: statistics.materialTypeStats.map(stat => ({
                            name: stat.type,
                            value: stat.count
                        })),
                        emphasis: {
                            itemStyle: {
                                shadowBlur: 10,
                                shadowOffsetX: 0,
                                shadowColor: 'rgba(0, 0, 0, 0.5)'
                            }
                        }
                    }
                ]
            };
            materialTypeChart.setOption(materialTypeOptions);

            // 显示申请列表（移除部门相关列）
            const tableBody = document.getElementById('application-table-body');
            tableBody.innerHTML = '';

            if (statistics.applicationList.length === 0) {
                const noDataRow = document.createElement('tr');
                noDataRow.innerHTML = `<td colspan="6" style="text-align: center; color: #999;">没有找到匹配的申请记录</td>`;
                tableBody.appendChild(noDataRow);
                return;
            }

            statistics.applicationList.forEach(application => {
                const row = document.createElement('tr');

                let statusText = '';
                if (application.status === 'APPROVED') {
                    statusText = '<span style="color: #059669;">已批准</span>';
                } else if (application.status === 'REJECTED') {
                    statusText = '<span style="color: #b91c1c;">已拒绝</span>';
                } else if (application.status === 'PENDING') {
                    statusText = '<span style="color: #856404;">待审批</span>';
                }

                row.innerHTML = `
                    <td>${application.materialName}</td>
                    <td>${application.materialType}</td>
                    <td>${application.quantity}</td>
                    <td>${application.applicant}</td>
                    <td>${application.applyDate}</td>
                    <td>${statusText}</td>
                `;

                tableBody.appendChild(row);
            });
        }

        function logout() {
            window.location.href = "../../login.html";
        }
    </script>
</head>
<body>
<div class="admin-layout">
    <!-- 顶部导航栏 -->
    <header class="admin-header">
        <div class="header-left">
            <div class="logo">生产过程管理系统</div>
        </div>
        <div class="header-right">
            <span class="user-info">部门经理</span>
            <span class="user-name">
                    <script>
                        try {
                            const userInfo = localStorage.getItem('userInfo');
                            const user = JSON.parse(userInfo);
                            document.write(user.name || '未登录');
                        } catch (e) {
                            document.write('未登录');
                        }
                    </script>
                </span>
            <button class="logout-btn" onclick="logout()">退出</button>
        </div>
    </header>

    <!-- 左侧菜单 -->
    <aside class="admin-sidebar">
        <ul class="menu-list">
            <li class="menu-item">
                <a href="homepage/manager_home.html">
                    <span class="menu-icon">🏠</span>
                    <span class="menu-title">首页</span>
                </a>
            </li>
            <li class="menu-item">
                <a href="javascript:void(0)">
                    <span class="menu-icon">👥</span>
                    <span class="menu-title">人员管理</span>
                    <span class="menu-arrow"></span>
                </a>
                <ul class="submenu">
                    <li><a href="../person/person_list.html">人员列表</a></li>
                    <li><a href="../person/person_edit.html" class="active">添加人员</a></li>
                    <li><a href="../person/schedule_edit.html">编辑排班表</a></li>
                    <li><a href="../person/schedule.html">查看排班表</a></li>
                    <li><a href="../person/schedule_statistics.html">班次统计</a></li>
                </ul>
            </li>
            <li class="menu-item">
                <a href="javascript:void(0)">
                    <span class="menu-icon">📦</span>
                    <span class="menu-title">物料管理</span>
                    <span class="menu-arrow"></span>
                </a>
                <ul class="submenu">
                    <li><a href="../material/material_list.html">物料列表</a></li>
                    <li><a href="../material/material_statistics.html">物料采购统计</a></li>
                </ul>
            </li>
            <li class="menu-item">
                <a href="javascript:void(0)">
                    <span class="menu-icon">⚙️</span>
                    <span class="menu-title">设备管理</span>
                    <span class="menu-arrow"></span>
                </a>
                <ul class="submenu">
                    <li><a href="../device/device_list.html">设备列表</a></li>
                    <li><a href="*">设备报修报废统计</a></li>
                </ul>
            </li>
            <li class="menu-item">
                <a href="javascript:void(0)">
                    <span class="menu-icon">📝</span>
                    <span class="menu-title">产品管理</span>
                    <span class="menu-arrow"></span>
                </a>
                <ul class="submenu">
                    <li><a href="../product/product_list.html">产品列表</a></li>
                    <li><a href="../product/editproduct_plan.html">编辑生产计划</a></li>
                    <li><a href="../product/viewproduct_plan.html">查看生产计划</a></li>
                </ul>
            </li>
            <li class="menu-item">
                <a href="javascript:void(0)">
                    <span class="menu-icon">🏢</span>
                    <span class="menu-title">供应商管理</span>
                    <span class="menu-arrow"></span>
                </a>
                <ul class="submenu">
                    <li><a href="../provider/provider_list.html">供应商列表</a></li>
                </ul>
            </li>
        </ul>
    </aside>

    <!-- 主内容区域 -->
    <main class="admin-main">
        <div class="content-wrapper">
            <h1>采购信息统计</h1>

            <!-- 保留关键词搜索框（简化筛选） -->
            <div style="margin-bottom: 20px; display: flex; align-items: center;">
                <label for="keyword-search" style="margin-right: 10px; font-weight: bold;">搜索:</label>
                <input type="text" id="keyword-search" placeholder="搜索物料名称或申请人" style="padding: 8px 12px; border: 1px solid #ddd; border-radius: 4px; min-width: 200px;">
                <button class="btn btn-secondary" id="search-btn" style="margin-left: 10px;">搜索</button>
            </div>

            <!-- 统计卡片 -->
            <div class="stat-container">
                <div class="stat-card">
                    <div class="stat-title">总申请数</div>
                    <div style="font-size: 36px; font-weight: bold; color: #17a2b8;">
                        <span id="total-applications">0</span>
                    </div>
                </div>
                <div class="stat-card">
                    <div class="stat-title">已批准申请</div>
                    <div style="font-size: 36px; font-weight: bold; color: #28a745;">
                        <span id="approved-applications">0</span>
                    </div>
                </div>
                <div class="stat-card">
                    <div class="stat-title">已拒绝申请</div>
                    <div style="font-size: 36px; font-weight: bold; color: #dc3545;">
                        <span id="rejected-applications">0</span>
                    </div>
                </div>
                <div class="stat-card">
                    <div class="stat-title">待审批申请</div>
                    <div style="font-size: 36px; font-weight: bold; color: #fd7e14;">
                        <span id="pending-applications">0</span>
                    </div>
                </div>
            </div>

            <!-- 统计图表（仅保留物料类型饼图） -->
            <div class="stat-container">
                <div class="stat-card" style="flex: 1; min-width: 400px;">
                    <div class="stat-title">各类型物料采购数量分布</div>
                    <div class="chart-container" id="material-type-chart"></div>
                </div>
            </div>

            <!-- 申请列表（移除部门相关列） -->
            <h2>采购申请明细</h2>
            <div class="table-container">
                <table class="stat-table">
                    <thead>
                    <tr>
                        <th>物料名称</th>
                        <th>材料类型</th>
                        <th>申请数量</th>
                        <th>申请人</th>
                        <th>申请日期</th>
                        <th>状态</th>
                    </tr>
                    </thead>
                    <tbody id="application-table-body">
                    <!-- 申请数据将通过JavaScript动态生成 -->
                    </tbody>
                </table>
            </div>
        </div>
    </main>
</div>
</body>
</html>